package com.renwen.sms.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.renwen.sms.dao.ClassDao;

import com.renwen.sms.dao.TeacherDao;
import com.renwen.sms.dto.ClassDto;

import com.renwen.sms.dto.PageResult;
import com.renwen.sms.entity.Class;

import com.renwen.sms.entity.SelectTeacher;
import com.renwen.sms.entity.Teacher;
import com.renwen.sms.exception.MyRuntimeException;
import com.renwen.sms.service.ClassService;

import com.renwen.sms.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ClassServiceImpl implements ClassService {
    @Resource
    ClassDao classDao;
    @Resource
    TeacherDao teacherDao;

    /**
     * 分页查询所有班级信息
     *
     * @param page      页码
     * @param size      每页显示条数
     * @param searchMap 搜索条件
     * @return 班级表信息
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public PageResult<ClassDto> list(Integer page, Integer size, Map<String, Object> searchMap) {
        // 构建查询条件
        //搜索框模糊查询
        QueryWrapper<Class> classQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
        if (!ObjectUtil.hasEmpty(searchMap)) {
            if (!ObjectUtil.hasEmpty(searchMap.get("name"))) {
                classQueryWrapper.like("cls_name", searchMap.get("name"));
            }
            if (!ObjectUtil.hasEmpty(searchMap.get("major"))) {
                classQueryWrapper.like("major", searchMap.get("major"));
            }
        }
        classQueryWrapper.select("cls_no", "cls_name", "major", "id");
        // 根据cls_no降序排序
        classQueryWrapper.orderByDesc("cls_no");
        Page<Class> classPage = classDao.selectPage(new Page<Class>(page, size), classQueryWrapper);
        List<ClassDto> cds = new ArrayList<>();
        ClassDto classDto = new ClassDto();
        //遍历班级信息
        for (Class aClass : classPage.getRecords()) {
            //根据班级号查询班主任信息
            teacherQueryWrapper.eq("cls_no", aClass.getClsNo());
            Teacher teacher = teacherDao.selectOne(teacherQueryWrapper);
            //存放课程信息对象
            //拷贝属性
            BeanUtils.copyProperties(aClass, classDto);
            //判断当前是否安排了班主任
            if (teacher != null) {
                classDto.setTName(teacher.getTName());
            }else {
                classDto.setTName("暂无");
            }
            //清空查询条件
            teacherQueryWrapper.clear();
            //添加教师信息到数组
            cds.add(classDto);
            //重新开辟内存地址
            classDto = new ClassDto();
        }
        return new PageResult<ClassDto>(cds, classPage.getTotal());
    }


    /**
     * 添加班级
     *
     * @param aClass 班级对象
     */
    @Override
    public void save(Class aClass) {
        // 0. 验证班级号
        if (!ReUtil.isMatch("\\d{5,8}$", aClass.getClsNo())) {
            throw new MyRuntimeException("班级号位数不对，5~8位");
        }else {
            QueryWrapper<Class> classQueryWrapper = new QueryWrapper<>();
            classQueryWrapper.eq("cls_no", aClass.getClsNo());
            Class aClass1 = classDao.selectOne(classQueryWrapper);
            if (aClass1 != null){
                throw new MyRuntimeException("当前班级号已经被占用！");
            }
           classQueryWrapper.clear();
        }
        // 1. 执行添加操作
        try {
            classDao.insert(aClass);
        } catch (Exception e) {
            throw new MyRuntimeException("添加班级出错！" + e.getMessage());
        }
    }

    /**
     * 根据班级编号查询班级信息
     *
     * @param id 班级编号
     * @return 班级信息
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    public Result get(Integer id) {
        if (!NumberUtil.isNumber(String.valueOf(id))) {
            throw new MyRuntimeException("编号应该是数字！");
        }
        try {
            Class aClass = classDao.selectById(id);
            ClassDto classDto = new ClassDto();
            BeanUtils.copyProperties(aClass, classDto);
            return new Result("查询成功", classDto);
        } catch (Exception e) {
            throw new MyRuntimeException("根据课程编号查询出错！" + e.getMessage());
        }
    }

    /**
     * 修改班级信息
     * @param aClass 班级对象
     */
    @Override
    public void update(Class aClass) {
        // 0. 验证班级号
        if (!ReUtil.isMatch("\\d{5,8}$", aClass.getClsNo())) {
            throw new MyRuntimeException("班级号格式不对！");
        }else {
            QueryWrapper<Class> classQueryWrapper = new QueryWrapper<>();
            classQueryWrapper.eq("cls_no", aClass.getClsNo());
            Class aClass1 = classDao.selectOne(classQueryWrapper);
            if (aClass1 != null){
                throw new MyRuntimeException("当前班级号已经被占用！");
            }
            classQueryWrapper.clear();
        }
        // 2. 执行修改操作
        try {
            classDao.updateById(aClass);
        } catch (Exception e) {
            throw new MyRuntimeException("修改班级信息出错！" + e.getMessage());
        }
    }

    /**
     * 根据班级号删除
     */
    @Override
    public void delete(String clsNo) {
        Map<String, Object> map = new HashMap<>();
        map.put("cls_no", clsNo);
        try {
            classDao.deleteByMap(map);
        } catch (Exception e) {
            throw new MyRuntimeException("删除班级时出错！" + e.getMessage());
        }
    }

    /**
     * 批量删除课程信息
     * @param ids 课程编号列表
     */
    @Override
    public void batchDelete(String ids) {
        //字符串切割
        String[] strs = ids.split(",");
        List<Integer> ids1 = new ArrayList<>();
        for (String str : strs) {
            ids1.add(Integer.valueOf(str));
        }
        if (ObjectUtil.hasEmpty(ids1)) {
            throw new MyRuntimeException("请先选择要删除的班级！");
        }
        try {
            classDao.deleteBatchIds(ids1);
        } catch (Exception e) {
            throw new MyRuntimeException("批量删除失败！" + e.getMessage());
        }
    }

    /**
     * 为未安排班主任的班级指定课程教师
     * @param selectTeacher 指定的教师信息
     */
    @Override
    public void selectTeacher(SelectTeacher selectTeacher) {
        try {
            //根据班级号查询当前教师信息
            QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
            teacherQueryWrapper.eq("cls_no",selectTeacher.getNowClsNo());
            Teacher teacher = teacherDao.selectOne(teacherQueryWrapper);

            Teacher teacher1 = new Teacher();
            teacher1.setId(Integer.valueOf(selectTeacher.getId()));
            teacher1.setClsNo(selectTeacher.getNowClsNo());
            //判断当前教师是否为null
            if (teacher == null) {
                teacherDao.updateById(teacher1);
            } else {
                throw new MyRuntimeException("当前班级已有教师！");
            }
        }catch (Exception e){
            throw new MyRuntimeException("指定教师失败！" + e.getMessage());
        }
    }
}
